import { Message } from 'element-ui'

import { SUPER_MANAGE_HOST } from '@/api/server'
import { getToken } from './auth'

/**
 * Parse the time to string
 * @param {(Object|string|number)} time
 * @param {string} cFormat
 * @returns {string | null}
 */
export function parseTime(time, cFormat) {
  if (arguments.length === 0 || !time) {
    return null
  }
  const format = cFormat || '{y}-{m}-{d} {h}:{i}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if (typeof time === 'string') {
      if (/^[0-9]+$/.test(time)) {
        // support "1548221490638"
        time = parseInt(time)
      } else {
        // support safari
        // https://stackoverflow.com/questions/4310953/invalid-date-in-safari
        time = time.replace(new RegExp(/-/gm), '/')
      }
    }

    if (typeof time === 'number' && time.toString().length === 10) {
      time = time * 1000
    }
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay(),
    t: date.getHours()
  }
  const time_str = format.replace(/{([ymdhisat])+}/g, (result, key) => {
    const value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') {
      return ['日', '一', '二', '三', '四', '五', '六'][value]
    }
    if (key === 't') {
      if (value > 0 && value <= 12) return '上午'
      else if (value > 12 && value <= 18) return '下午'
      else return '晚上'
    }
    return value.toString().padStart(2, '0')
  })

  return time_str
}

/**
 * @param {number} time
 * @param {string} option
 * @returns {string}
 */
export function formatTime(time, option) {
  if (('' + time).length === 10) {
    time = parseInt(time) * 1000
  } else {
    time = +time
  }
  const d = new Date(time)
  const now = Date.now()

  const diff = (now - d) / 1000

  if (diff < 30) {
    return '刚刚'
  } else if (diff < 3600) {
    // less 1 hour
    return Math.ceil(diff / 60) + '分钟前'
  } else if (diff < 3600 * 24) {
    return Math.ceil(diff / 3600) + '小时前'
  } else if (diff < 3600 * 24 * 2) {
    return '1天前'
  }
  if (option) {
    return parseTime(time, option)
  } else {
    return (
      d.getMonth() +
      1 +
      '月' +
      d.getDate() +
      '日' +
      d.getHours() +
      '时' +
      d.getMinutes() +
      '分'
    )
  }
}

export function parseDate(time) {
  return parseTime(time, '{y}-{m}-{d}')
}

/**
 * @param {string} url
 * @returns {Object}
 */
export function getQueryObject(url) {
  url = url === null ? window.location.href : url
  const search = url.substring(url.lastIndexOf('?') + 1)
  const obj = {}
  const reg = /([^?&=]+)=([^?&=]*)/g
  search.replace(reg, (rs, $1, $2) => {
    const name = decodeURIComponent($1)
    let val = decodeURIComponent($2)
    val = String(val)
    obj[name] = val
    return rs
  })
  return obj
}

/**
 * @param {string} input value
 * @returns {number} output value
 */
export function byteLength(str) {
  // returns the byte length of an utf8 string
  let s = str.length
  for (var i = str.length - 1; i >= 0; i--) {
    const code = str.charCodeAt(i)
    if (code > 0x7f && code <= 0x7ff) s++
    else if (code > 0x7ff && code <= 0xffff) s += 2
    if (code >= 0xdc00 && code <= 0xdfff) i--
  }
  return s
}

/**
 * @param {Array} actual
 * @returns {Array}
 */
export function cleanArray(actual) {
  const newArray = []
  for (let i = 0; i < actual.length; i++) {
    if (actual[i]) {
      newArray.push(actual[i])
    }
  }
  return newArray
}

/**
 * @param {Object} json
 * @returns {Array}
 */
export function param(json) {
  if (!json) return ''
  return cleanArray(
    Object.keys(json).map(key => {
      if (json[key] === undefined) return ''
      return encodeURIComponent(key) + '=' + encodeURIComponent(json[key])
    })
  ).join('&')
}

/**
 * @param {string} url
 * @returns {Object}
 */
export function param2Obj(url) {
  const search = decodeURIComponent(url.split('?')[1]).replace(/\+/g, ' ')
  if (!search) {
    return {}
  }
  const obj = {}
  const searchArr = search.split('&')
  searchArr.forEach(v => {
    const index = v.indexOf('=')
    if (index !== -1) {
      const name = v.substring(0, index)
      const val = v.substring(index + 1, v.length)
      obj[name] = val
    }
  })
  return obj
}

/**
 * @param {string} val
 * @returns {string}
 */
export function html2Text(val) {
  const div = document.createElement('div')
  div.innerHTML = val
  return div.textContent || div.innerText
}

/**
 * Merges two objects, giving the last one precedence
 * @param {Object} target
 * @param {(Object|Array)} source
 * @returns {Object}
 */
export function objectMerge(target, source) {
  if (typeof target !== 'object') {
    target = {}
  }
  if (Array.isArray(source)) {
    return source.slice()
  }
  Object.keys(source).forEach(property => {
    const sourceProperty = source[property]
    if (typeof sourceProperty === 'object') {
      target[property] = objectMerge(target[property], sourceProperty)
    } else {
      target[property] = sourceProperty
    }
  })
  return target
}

/**
 * @param {HTMLElement} element
 * @param {string} className
 */
export function toggleClass(element, className) {
  if (!element || !className) {
    return
  }
  let classString = element.className
  const nameIndex = classString.indexOf(className)
  if (nameIndex === -1) {
    classString += '' + className
  } else {
    classString =
      classString.substr(0, nameIndex) +
      classString.substr(nameIndex + className.length)
  }
  element.className = classString
}

/**
 * @param {string} type
 * @returns {Date}
 */
export function getTime(type) {
  if (type === 'start') {
    return new Date().getTime() - 3600 * 1000 * 24 * 90
  } else {
    return new Date(new Date().toDateString())
  }
}

export const DateRange = {
  todayRange() {
    const end = new Date()
    const start = new Date(new Date().toDateString())
    end.setTime(start.getTime() + 3600 * 1000 * 24 * 1)
    return [start, end]
  },
  yesterdayRange() {
    const end = new Date(new Date().toDateString())
    const start = new Date()
    start.setTime(end.getTime() - 3600 * 1000 * 24 * 1)
    return [start, end]
  },
  lastThreeDay() {
    const end = new Date(new Date().toDateString())
    const start = new Date()
    start.setTime(end.getTime() - 3600 * 1000 * 24 * 2)
    end.setTime(end.getTime() + 3600 * 1000 * 24 * 1)
    return [start, end]
  },
  lastSevenDay() {
    const end = new Date(new Date().toDateString())
    const start = new Date()
    start.setTime(end.getTime() - 3600 * 1000 * 24 * 6)
    end.setTime(end.getTime() + 3600 * 1000 * 24 * 1)
    return [start, end]
  },
  customDay(start, days) {
    const startDate = new Date(new Date(start).toString())
    startDate.setTime(startDate.getTime() + 3600 * 1000 * 24 * days)
    return startDate
  },
  customRange(start, end) {
    const startDate = new Date(start)
    const endDate = new Date(new Date(end).toDateString())
    endDate.setTime(endDate.getTime() + 3600 * 1000 * 24 * 1)
    return [startDate, endDate]
  }
}

/**
 * @param {Function} func
 * @param {number} wait
 * @param {boolean} immediate
 * @return {*}
 */
export function debounce(func, wait, immediate) {
  let timeout, args, context, timestamp, result

  const later = function() {
    // 据上一次触发时间间隔
    const last = +new Date() - timestamp

    // 上次被包装函数被调用时间间隔 last 小于设定时间间隔 wait
    if (last < wait && last > 0) {
      timeout = setTimeout(later, wait - last)
    } else {
      timeout = null
      // 如果设定为immediate===true，因为开始边界已经调用过了此处无需调用
      if (!immediate) {
        result = func.apply(context, args)
        if (!timeout) context = args = null
      }
    }
  }

  return function(...args) {
    context = this
    timestamp = +new Date()
    const callNow = immediate && !timeout
    // 如果延时不存在，重新设定延时
    if (!timeout) timeout = setTimeout(later, wait)
    if (callNow) {
      result = func.apply(context, args)
      context = args = null
    }

    return result
  }
}

/**
 * This is just a simple version of deep copy
 * Has a lot of edge cases bug
 * If you want to use a perfect deep copy, use lodash's _.cloneDeep
 * @param {Object} source
 * @returns {Object}
 */
export function deepClone(source = {}) {
  const targetObj = source.constructor === Array ? [] : {}

  Object.keys(source).forEach(keys => {
    if (source[keys] && typeof source[keys] === 'object') {
      targetObj[keys] = deepClone(source[keys])
    } else {
      targetObj[keys] = source[keys]
    }
  })

  return targetObj
}

/**
 * @param {Array} arr
 * @returns {Array}
 */
export function uniqueArr(arr) {
  return Array.from(new Set(arr))
}

/**
 * @returns {string}
 */
export function createUniqueString() {
  const timestamp = +new Date() + ''
  const randomNum = parseInt((1 + Math.random()) * 65536) + ''
  return (+(randomNum + timestamp)).toString(32)
}

/**
 * Check if an element has a class
 * @param {HTMLElement} elm
 * @param {string} cls
 * @returns {boolean}
 */
export function hasClass(ele, cls) {
  return !!ele.className.match(new RegExp('(\\s|^)' + cls + '(\\s|$)'))
}

/**
 * Add class to element
 * @param {HTMLElement} elm
 * @param {string} cls
 */
export function addClass(ele, cls) {
  if (!hasClass(ele, cls)) ele.className += ' ' + cls
}

/**
 * Remove class from element
 * @param {HTMLElement} elm
 * @param {string} cls
 */
export function removeClass(ele, cls) {
  if (hasClass(ele, cls)) {
    const reg = new RegExp('(\\s|^)' + cls + '(\\s|$)')
    ele.className = ele.className.replace(reg, ' ')
  }
}

const arabicMap = {
  1: '一',
  2: '二',
  3: '三',
  4: '四',
  5: '五',
  6: '六',
  7: '七',
  8: '八',
  9: '九',
  10: '十'
}
/**
 * 阿拉伯数字转汉字数字
 * 1 => 一
 * 2 => 二
 * ...
 */
export function arabic2cn(number) {
  return arabicMap[number] || '一'
}

const arabicMap2 = {
  1: 'A',
  2: 'B',
  3: 'C',
  4: 'D',
  5: 'E',
  6: 'F',
  7: 'G',
  8: 'H',
  9: 'I',
  10: 'J',
  11: 'K',
  12: 'L',
  13: 'M',
  14: 'N',
  15: 'O',
  16: 'P',
  17: 'Q',
  18: 'R',
  19: 'S',
  20: 'T',
  21: 'U',
  22: 'V',
  23: 'W',
  24: 'X',
  25: 'Y',
  26: 'Z'
}
/**
 * 阿拉伯数字转大写英文字母
 * @param {*} number
 * 1 => A
 * 2 => B
 */
export function arabic2en(number) {
  return arabicMap2[number] || 'A'
}

/**
 * 编辑器配置
 */
export const editorConfig = {
  // 关闭粘贴样式的过滤
  pasteFilterStyle: false,

  menus: [
    'fontName',
    'fontSize',
    'lineHeight',
    'foreColor',
    'bold',
    'link',
    'italic',
    'underline',
    'backColor',
    'undo',
    'image',
    'code'
  ],

  // 上传图片配置
  uploadImgServer: `${SUPER_MANAGE_HOST}/company/attachment/upload`,
  uploadImgMaxLength: 1,
  withCredentials: true,
  uploadFileName: 'file',

  // 上传图片的类型
  uploadImgAccept: ['jpg', 'jpeg', 'png', 'gif', 'bmp'],

  uploadImgHooks: {
    before(xhr, editor, files) {
      xhr.setRequestHeader('Authorization', 'Bearer ' + getToken())
    },

    // 图片上传并返回了结果，想要自己把图片插入到编辑器中
    // 服务器端返回 { code: 0, data: '', message }
    customInsert(insertImgFn, res) {
      // res 即服务端返回的接口
      const { code, data, message } = res

      if (code === 0) {
        // insertImgFn 可把图片插入到编辑器，传入图片 src ，执行函数即可
        insertImgFn(data)
      } else {
        Message({
          type: 'error',
          message
        })
      }
    }
  },

  customAlert(msg) {
    Message({
      type: 'error',
      message: msg
    })
  },

  // 隐藏上传网络图片tab
  showLinkImg: false,

  zIndex: 1,

  // 取消编辑器自动获取焦点
  focus: false,

  // 配置全屏功能按钮是否展示
  showFullScreen: true
}

/**
 * 判断是否是空html标签
 * @param {*} content
 * @returns
 */
export function isEmptyHTML(content) {
  return /<div[^>]*><\/div>/.test(content)
}

/**
 * 过滤编辑器br标签
 * @param {*} content
 * @returns
 */
export function editorFilter(content = '') {
  return content.replace(/<xmp>[\s\S]*?<\/xmp>/g, str => {
    return str.replace(/<br\/*>/g, '\n')
  })
}

/**
 * 交换数组中两个元素位置
 * @param {*} arr
 * @param {*} index1
 * @param {*} index2
 */
export function swap(arr, index1, index2) {
  arr.splice(index2, 1, ...arr.splice(index1, 1, arr[index2]))
}

/**
 * 延迟一定毫秒后执行
 * @param {*} delay
 */
export function sleep(delay) {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve()
    }, delay)
  })
}

/**
 * 秒转分钟
 * @param {*} second
 */
export function second2minute(second) {
  return Math.round(second / 60)
}

/**
 * 分钟转秒
 * @param {*} minute
 */
export function minute2second(minute) {
  return minute * 60
}

/**
 * 比较时间相差值
 * @param {*} time1
 * @param {*} time2
 */
export function timeDifference(time1, time2) {
  // 判断开始时间是否大于结束日期

  if (time1 > time2) {
    return -1
  }

  // 截取字符串，得到日期部分"2009-12-02",用split把字符串分隔成数组
  // var begin1 = time1.substr(0, 10).split('-')
  // var end1 = time2.substr(0, 10).split('-')

  // 将拆分的数组重新组合，并实例成化新的日期对象
  // var date1 = new Date(begin1[1] + '-' + begin1[2] + '-' + begin1[0])
  // var date2 = new Date(end1[1] + '-' + end1[2] + '-' + end1[0])
  var date1 = new Date(time1.substr(0, 10))
  var date2 = new Date(time2.substr(0, 10))

  // 得到两个日期之间的差值m，以分钟为单位
  // Math.abs(date2-date1)计算出以毫秒为单位的差值
  // Math.abs(date2-date1)/1000得到以秒为单位的差值
  // Math.abs(date2-date1)/1000/60得到以分钟为单位的差值
  var m = parseInt(Math.abs(date2 - date1) / 1000 / 60)

  // 小时数和分钟数相加得到总的分钟数
  // time1.substr(11,2)截取字符串得到时间的小时数
  // parseInt(time1.substr(11,2))*60把小时数转化成为分钟
  var min1 = parseInt(time1.substr(11, 2)) * 60 + parseInt(time1.substr(14, 2))
  var min2 = parseInt(time2.substr(11, 2)) * 60 + parseInt(time2.substr(14, 2))

  // 两个分钟数相减得到时间部分的差值，以分钟为单位
  var n = min2 - min1

  // 将日期和时间两个部分计算出来的差值相加，即得到两个时间相减后的分钟数
  var minutes = m + n

  return minutes
}

/**
 * @params value
 * 获取字节长度
 */
export function GetCharLength(str) {
  var iLength = 0 // 记录字符的字节数
  for (var i = 0; i < str.length; i++) {
    // 遍历字符串中的每个字符
    if (str.charCodeAt(i) > 255) {
      // 如果当前字符的编码大于255
      iLength += 2 // 所占字节数加2
    } else {
      iLength += 1 // 否则所占字节数加1
    }
  }

  return iLength // 返回字符所占字节数
}

export function getFormatDate(timeStamp) {
  var date = new Date(timeStamp)
  var seperator1 = '-'
  var seperator2 = ':'
  var month = date.getMonth() + 1
  var strDate = date.getDate()
  if (month >= 1 && month <= 9) {
    month = '0' + month
  }
  if (strDate >= 0 && strDate <= 9) {
    strDate = '0' + strDate
  }
  var currentdate = date.getYear() + seperator1 + month + seperator1 + strDate +
          ' ' + date.getHours() + seperator2 + date.getMinutes() +
          seperator2 + date.getSeconds()
  return currentdate
}

// 获取富文本中纯文本文字（包含英文）长度
export function getTextLength(html) {
  const dom = document.createElement('div')
  if (html && html.indexOf('<br/>') > -1) {
    dom.innerHTML = html.replace('<br/>', '')
  } else {
    dom.innerHTML = html
  }
  const length = dom.innerText.replace(/\s+/g, '').length
  // const length = recurGetText(0, dom.childNodes)
  return length
}

// 判断设备是否为手机端
export function IsPhone() {
  const info = navigator.userAgent
  const isPhone = /mobile/i.test(info)
  return isPhone
}

export function dataURLtoFile(dataurl, filename) {
  var arr = dataurl.split(',')
  var res = arr[0].match(/:(.*?);/)
  if (!res) return
  const mime = res[1]
  var bstr = atob(arr[1])
  var n = bstr.length
  var u8arr = new Uint8Array(n)
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n)
  }
  return new File([u8arr], filename, { type: mime })
}

export function readImg(file) {
  return new Promise((resolve, reject) => {
    const img = new Image()
    const reader = new FileReader()
    reader.onload = (e) => {
      img.src = e.target.result
    }
    reader.onerror = (error) => {
      reject(error)
    }
    reader.readAsDataURL(file)
    img.onload = () => {
      resolve(img)
    }
    img.onerror = (e) => {
      reject(e)
    }
  })
}
